package com.busfm.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class DBProvider extends ContentProvider {
	public static final String DBNAME = "busfm";
	public static int DBVERSION = 1;
	private static final String PARAMETER_NOTIFY = "notify";
	public static final String TAB_DOWNLOAD = "download";

	public static final String AUTHORITY = "com.busfm";

	public static final String COL_ID = "_id";
	public static final String COL_SONGID = "song_id";
	public static final String COL_NAME = "name";
	public static final String COL_PATH = "path";
	public static final String COL_TOTAL_SIZE = "totalSize";
	public static final String COL_ARTIST = "artist";
	public static final String COL_ALBUM = "album";
	public static final String COL_DOWNLOADED = "downloaded";

	public static final Uri CONTENT_URI_DOWNLOAD = Uri.parse("content://"
			+ AUTHORITY + "/" + TAB_DOWNLOAD);

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DBNAME, null, DBVERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TAB_DOWNLOAD + " (" + COL_ID
					+ " Integer PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, "
					+ COL_SONGID + " TEXT, " + COL_NAME + " TEXT, " + COL_PATH
					+ " TEXT, " + COL_ALBUM + " TEXT," + COL_DOWNLOADED
					+ " INTEGER, " + COL_TOTAL_SIZE + " INTEGER, " + COL_ARTIST
					+ " TEXT );");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if (newVersion > oldVersion) {
				db.execSQL("DROP TABLE IF EXISTS " + TAB_DOWNLOAD);
			}
		}

	}

	private SQLiteOpenHelper mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return false;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = db.delete(args.table, args.where, args.args);

		if (count > 0) {
			sendNotify(uri);
		}

		return count;
	}

	@Override
	public String getType(Uri uri) {
		SqlArguments args = new SqlArguments(uri, null, null);
		if (TextUtils.isEmpty(args.where)) {
			return "vnd.android.cursor.dir/" + args.table;
		} else {
			return "vnd.android.cursor.item/" + args.table;
		}
	}

	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		SqlArguments args = new SqlArguments(uri);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			int numValues = values.length;

			for (int i = 0; i < numValues; i++) {

				if (db.insert(args.table, null, values[i]) < 0) {
					return 0;
				}
			}

			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}

		sendNotify(uri);
		return values.length;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SqlArguments args = new SqlArguments(uri);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		final long rowId = db.insert(args.table, null, values);

		if (rowId <= 0) {
			return null;
		}

		uri = ContentUris.withAppendedId(uri, rowId);
		sendNotify(uri);

		return uri;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(args.table);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor result = qb.query(db, projection, args.where, args.args, null,
				null, sortOrder);
		result.setNotificationUri(getContext().getContentResolver(), uri);

		return result;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = db.update(args.table, values, args.where, args.args);

		if (count > 0) {
			sendNotify(uri);
		}

		return count;
	}

	private void sendNotify(Uri uri) {
		String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
		if ((null == notify) || ("true".equals(notify))) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
	}

	private static final class SqlArguments {
		public final String table;
		public final String where;
		public final String[] args;

		public SqlArguments(Uri url) {
			if (url.getPathSegments().size() == 1) {
				table = url.getPathSegments().get(0);
				where = null;
				args = null;
			} else {
				throw new IllegalArgumentException("Invalid URI: " + url);
			}
		}

		public SqlArguments(Uri url, String where, String[] args) {
			if (url.getPathSegments().size() == 1) {
				this.table = url.getPathSegments().get(0);
				this.where = where;
				this.args = args;
			} else if (url.getPathSegments().size() != 2) {
				throw new IllegalArgumentException("Invalid URI: " + url);
			} else if (!TextUtils.isEmpty(where)) {
				throw new UnsupportedOperationException(
						"WHERE clause not supported: " + url);
			} else {
				this.table = url.getPathSegments().get(0);
				this.where = "_id=" + ContentUris.parseId(url);
				this.args = null;
			}
		}

	}

}
